package com.music.note_android.ui.notelist

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.music.note_android.data.model.Note
import com.music.note_android.data.repository.NoteRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 笔记列表ViewModel
 * 管理笔记列表页面的业务逻辑和状态
 */
@HiltViewModel
class NoteListViewModel @Inject constructor(
    private val repository: NoteRepository
) : ViewModel() {
    
    // 搜索查询状态
    private val _searchQuery = MutableStateFlow("")
    val searchQuery: StateFlow<String> = _searchQuery.asStateFlow()
    
    // 文件夹过滤状态
    private val _folderId = MutableStateFlow<String?>(null)
    val folderId: StateFlow<String?> = _folderId.asStateFlow()
    
    // 加载状态
    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()
    
    // 搜索结果
    private val _searchResults = MutableStateFlow<List<Note>>(emptyList())
    val searchResults: StateFlow<List<Note>> = _searchResults.asStateFlow()
    
    // 选择模式状态
    private val _isSelectionMode = MutableStateFlow(false)
    val isSelectionMode: StateFlow<Boolean> = _isSelectionMode.asStateFlow()
    
    // 选中的笔记ID列表
    private val _selectedNoteIds = MutableStateFlow<Set<String>>(emptySet())
    val selectedNoteIds: StateFlow<Set<String>> = _selectedNoteIds.asStateFlow()
    
    // 错误消息
    private val _errorMessage = MutableStateFlow<String?>(null)
    val errorMessage: StateFlow<String?> = _errorMessage.asStateFlow()
    
    // 搜索防抖Job
    private var searchJob: Job? = null
    
    // 获取笔记的Flow（支持文件夹过滤）
    val notes: StateFlow<List<Note>> = _folderId.flatMapLatest { folderId ->
        if (folderId != null) {
            repository.getNotesByFolder(folderId)
        } else {
            repository.getAllNotes()
        }
    }.catch { exception ->
        _errorMessage.value = "加载笔记失败: ${exception.message}"
        emit(emptyList())
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = emptyList()
    )
    
    // 当前显示的笔记列表（搜索时显示搜索结果，否则显示所有笔记）
    val displayNotes: StateFlow<List<Note>> = combine(
        notes,
        searchResults,
        searchQuery
    ) { allNotes, searchResults, query ->
        if (query.isBlank()) {
            allNotes
        } else {
            searchResults
        }
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = emptyList()
    )
    
    /**
     * 搜索笔记
     */
    fun searchNotes(query: String) {
        _searchQuery.value = query
        
        // 取消之前的搜索任务
        searchJob?.cancel()
        
        if (query.isBlank()) {
            _searchResults.value = emptyList()
            return
        }
        
        // 防抖搜索
        searchJob = viewModelScope.launch {
            delay(300) // 300ms防抖延迟
            try {
                _isLoading.value = true
                val results = repository.searchNotes(query)
                _searchResults.value = results
            } catch (exception: Exception) {
                _errorMessage.value = "搜索失败: ${exception.message}"
                _searchResults.value = emptyList()
            } finally {
                _isLoading.value = false
            }
        }
    }
    
    /**
     * 清除搜索
     */
    fun clearSearch() {
        searchJob?.cancel()
        _searchQuery.value = ""
        _searchResults.value = emptyList()
    }
    
    /**
     * 创建新笔记
     */
    fun createNewNote() {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                val note = repository.createNote("")
                // 这里可以添加导航到编辑页面的逻辑
            } catch (exception: Exception) {
                _errorMessage.value = "创建笔记失败: ${exception.message}"
            } finally {
                _isLoading.value = false
            }
        }
    }
    
    /**
     * 删除单个笔记
     */
    fun deleteNote(noteId: String) {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                repository.deleteNote(noteId)
            } catch (exception: Exception) {
                _errorMessage.value = "删除笔记失败: ${exception.message}"
            } finally {
                _isLoading.value = false
            }
        }
    }
    
    /**
     * 批量删除选中的笔记
     */
    fun deleteSelectedNotes() {
        val selectedIds = _selectedNoteIds.value.toList()
        if (selectedIds.isEmpty()) return
        
        viewModelScope.launch {
            try {
                _isLoading.value = true
                repository.deleteNotes(selectedIds)
                clearSelection()
            } catch (exception: Exception) {
                _errorMessage.value = "删除笔记失败: ${exception.message}"
            } finally {
                _isLoading.value = false
            }
        }
    }
    
    /**
     * 重命名笔记
     */
    fun renameNote(noteId: String, newTitle: String) {
        viewModelScope.launch {
            try {
                repository.renameNote(noteId, newTitle)
            } catch (exception: Exception) {
                _errorMessage.value = "重命名失败: ${exception.message}"
            }
        }
    }
    
    /**
     * 进入选择模式
     */
    fun enterSelectionMode(noteId: String) {
        _isSelectionMode.value = true
        _selectedNoteIds.value = setOf(noteId)
    }
    
    /**
     * 退出选择模式
     */
    fun exitSelectionMode() {
        _isSelectionMode.value = false
        _selectedNoteIds.value = emptySet()
    }
    
    /**
     * 切换笔记选择状态
     */
    fun toggleNoteSelection(noteId: String) {
        val currentSelection = _selectedNoteIds.value.toMutableSet()
        if (currentSelection.contains(noteId)) {
            currentSelection.remove(noteId)
        } else {
            currentSelection.add(noteId)
        }
        _selectedNoteIds.value = currentSelection
        
        // 如果没有选中任何笔记，退出选择模式
        if (currentSelection.isEmpty()) {
            _isSelectionMode.value = false
        }
    }
    
    /**
     * 全选/取消全选
     */
    fun toggleSelectAll() {
        val currentNotes = displayNotes.value
        val currentSelection = _selectedNoteIds.value
        
        if (currentSelection.size == currentNotes.size) {
            // 当前全选状态，取消全选
            _selectedNoteIds.value = emptySet()
            _isSelectionMode.value = false
        } else {
            // 全选
            _selectedNoteIds.value = currentNotes.map { it.id }.toSet()
            _isSelectionMode.value = true
        }
    }
    
    /**
     * 清除选择
     */
    fun clearSelection() {
        _selectedNoteIds.value = emptySet()
        _isSelectionMode.value = false
    }
    
    /**
     * 清除错误消息
     */
    fun clearErrorMessage() {
        _errorMessage.value = null
    }
    
    /**
     * 检查笔记是否被选中
     */
    fun isNoteSelected(noteId: String): Boolean {
        return _selectedNoteIds.value.contains(noteId)
    }
    
    /**
     * 获取选中笔记数量
     */
    fun getSelectedCount(): Int {
        return _selectedNoteIds.value.size
    }
    
    /**
     * 设置文件夹过滤
     */
    fun setFolderFilter(folderId: String?) {
        _folderId.value = folderId
    }
    
    /**
     * 清除文件夹过滤
     */
    fun clearFolderFilter() {
        _folderId.value = null
    }
}